<template>
  <div class="ele-body">
    <ele-modal
      :width="1200"
      :visible="visible"
      :confirm-loading="loading"
      title="报名管理"
      :body-style="{ paddingBottom: '8px' }"
      @update:visible="updateVisible"
    >
      <!-- 表格 -->
      <ele-pro-table
        ref="tableRef"
        row-key="id"
        :columns="columns"
        :datasource="datasource"
        v-model:selection="selection"
        :scroll="{ x: 1000 }"
        :where="defaultWhere"
        :needPage="false"
        cache-key="proSignUserTable"
      >
        <template #toolbar>
          <a-space>
            <user-search :where="defaultWhere" @search="reload" />
          </a-space>
        </template>
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'isSign'">
            <a-tag v-if="record.isSign === 0" color="cyan">未签到</a-tag>
            <a-tag v-else color="red">已签到</a-tag>
          </template>
          <template v-else-if="column.key === 'row'">
            <a-input-number
              v-model:value="record.row"
              placeholder="行"
              @blur="enterSeat(record)"
            />
          </template>
          <template v-else-if="column.key === 'column'">
            <a-input-number
              v-model:value="record.column"
              placeholder="列"
              @blur="enterSeat(record)"
            />
          </template>
        </template>
      </ele-pro-table>
      <template #footer>
        <a-button type="primary" danger @click="dataExport">导出</a-button>
        <a-button type="primary" @click="close">关闭</a-button>
      </template>
    </ele-modal>
  </div>
</template>

<script lang="ts" setup>
  import { ref, reactive, watch } from 'vue';
  import type { EleProTable } from 'ele-admin-pro/es';
  import type {
    DatasourceFunction,
    ColumnItem
  } from 'ele-admin-pro/es/ele-pro-table/types';
  import { toDateString } from 'ele-admin-pro/es';
  import UserSearch from './user-search.vue';
  import { listUsers, updateSignUser } from '@/api/meeting';
  import type { User, UserParam } from '@/api/meeting/model';
  import { message } from 'ant-design-vue';
  import { utils, writeFile } from 'xlsx';

  const emit = defineEmits<{
    (e: 'done'): void;
    (e: 'update:visible', visible: boolean): void;
  }>();

  const props = defineProps<{
    // 弹窗是否打开
    visible: boolean;
    // 修改回显的数据
    data?: number | string;
  }>();
  // 表格实例
  const tableRef = ref<InstanceType<typeof EleProTable> | null>(null);

  // 提交状态
  const loading = ref(false);
  // 表格列配置
  const columns = ref<ColumnItem[]>([
    {
      key: 'index',
      width: 48,
      align: 'center',
      fixed: 'left',
      hideInSetting: true,
      customRender: ({ index }) => index + (tableRef.value?.tableIndex ?? 0)
    },
    {
      title: '姓名',
      dataIndex: 'name',
      sorter: true,
      showSorterTooltip: false
    },
    {
      title: '企业',
      dataIndex: 'company',
      sorter: true,
      showSorterTooltip: false
    },
    {
      title: '职位',
      dataIndex: 'position',
      width: 80,
      align: 'center',
      sorter: true,
      showSorterTooltip: false
    },
    {
      title: '手机号',
      dataIndex: 'phone',
      sorter: true,
      showSorterTooltip: false
    },
    {
      title: '座位排',
      key: 'row',
      dataIndex: 'row',
      sorter: true,
      showSorterTooltip: false
    },
    {
      title: '座位列',
      key: 'column',
      dataIndex: 'column',
      sorter: true,
      showSorterTooltip: false
    },
    {
      title: '报名时间',
      dataIndex: 'entry_time',
      sorter: true,
      showSorterTooltip: false,
      ellipsis: true,
      customRender: ({ text }) => toDateString(text, 'MM-dd HH:mm')
    },
    {
      title: '签到时间',
      dataIndex: 'sign_time',
      sorter: true,
      showSorterTooltip: false,
      ellipsis: true,
      customRender: ({ text }) => toDateString(text, 'MM-dd HH:mm')
    },
    {
      title: '是否签到',
      key: 'isSign',
      dataIndex: 'isSign',
      sorter: true,
      showSorterTooltip: false,
      width: 90,
      align: 'center'
    }
  ]);

  // 表格选中数据
  const selection = ref<User[]>([]);

  // 默认搜索条件
  const defaultWhere = reactive<{
    meetingId?: number | string;
    name?: string;
    company?: string;
  }>({
    meetingId: '',
    name: '',
    company: ''
  });

  // 表格数据源

  const datasource: DatasourceFunction = ({ where, orders }) => {
    return listUsers({ ...where, ...orders });
  };

  /* 搜索 */
  const reload = (where?: UserParam) => {
    selection.value = [];
    tableRef?.value?.reload({ page: 1, where });
  };

  /* 导出excel */
  const dataExport = () => {
    listUsers({ meetingId: defaultWhere.meetingId }).then((res) => {
      const array: (string | number | undefined)[][] = [
        [
          '序号',
          '会议id',
          '姓名',
          '单位',
          '职位',
          '电话',
          '是否签到(1:签到)',
          '座位排',
          '座位列',
          '报名时间',
          '签到时间'
        ]
      ];
      res.forEach((d, i) => {
        array.push([
          i + 1,
          d.meetingId,
          d.name,
          d.company,
          d.position,
          d.phone,
          d.isSign,
          d.row,
          d.column,
          d.entry_time,
          d.sign_time
        ]);
      });
      const sheetName = 'Sheet1';
      const workbook = {
        SheetNames: [sheetName],
        Sheets: {}
      };
      const sheet = utils.aoa_to_sheet(array);
      workbook.Sheets[sheetName] = sheet;
      writeFile(workbook, '签到数据.xlsx');
    });
  };

  const close = () => {
    updateVisible(false);
  };

  /* 更新visible */
  const updateVisible = (value: boolean) => {
    emit('update:visible', value);
  };

  const enterSeat = (value: any) => {
    updateSignUser(value).then((res) => {
      if (res.code !== 0) {
        message.error('出错了！');
      }
    });
  };
  watch(
    () => props.data,
    (value) => {
      defaultWhere.meetingId = value;
      reload();
    }
  );
</script>

<script lang="ts">
  export default {
    name: 'SignUser'
  };
</script>
